;(function () {
	// const todos = [
	// 	{
	// 		id: 1,
	// 		title: '吃饭',
	// 		completed: true
	// 	},
	// 	{
	// 		id: 2,
	// 		title: '睡觉',
	// 		completed: false
	// 	},
	// 	{
	// 		id: 3,
	// 		title: '写代码',
	// 		completed: false
	// 	}
	// ];

	Vue.directive('focus', {
		inserted: function (el) {
			el.focus();
		}
	});
	Vue.directive('todo-focus', {
		update: function (el, binding) {
			if(binding.value) {
				el.focus();
			}
		}
	});

	window.app = new Vue({
		data: {
			todos: JSON.parse(window.localStorage.getItem('todos') || '[]'),
			currentEditing: null,
			filterText: 'all'
		},
		computed: {
			remaingCount () {
				return this.todos.filter(t => !t.completed).length;
			},
			ToggleAllState: {
				get () {
					return this.todos.every(t => t.completed);
				}
			},
			filterTodos () {
				switch(this.filterText) {
					case 'active':
						return this.todos.filter(t => !t.completed);
						break;
					case 'completed':
						return this.todos.filter(t => t.completed);
						break;
					default:
						return this.todos;
						break;
				}
			}
		},
		watch: {
			todos: {
				handler () {
					window.localStorage.setItem('todos', JSON.stringify(this.todos))
				},
				deep: true
			}
		},
		methods: {
			AddTask (e) {
			// 0. 注册按下的回车事件
			// 1. 获取文本框的内容
			// 2. 数据校验
			// 3. 添加到todos 列表
			// 	const value = e.target.value.trim();
				const target = e.target;
				const value = target.value.trim();
			// console.log(value)
				if(!value.length) {
					return;
				}
				const todos = this.todos;
				todos.push({
					id: todos.length ? todos[todos.length-1].id + 1 : 1,
					title: value,
					completed: false
				});
				target.value = ''
			},
			handleToggleAllChange (e) {
				// console.log('all')
				const checked = e.target.checked;
				this.todos.forEach(item => {
					item.completed = checked;
				})
			},
			remove (index, e) {
				this.todos.splice(index, 1);
			},
			getEditing (todo) {
				this.currentEditing = todo;
			},
			saveEdite (todo, index, e) {
				const target = e.target;
				const value = target.value.trim();
				if(!value.length) {
					this.todos.splice(index, 1);
				}else {
					todo.title = value;
					this.currentEditing = null;
				}
			},
			cancelEdite () {
				this.currentEditing = null;
			},
			ClearAll () {
				for(let i=0; i<this.todos.length; i++){
					if(this.todos[i].completed) {
						this.todos.splice(i, 1);
						i--;
					}
				}
				// 使用过滤器重新赋值
				// this.todos = this.todos.filter(t => !t.completed)
			}
		}
	}).$mount('#app');

	window.onhashchange = function () {
		app.filterText = window.location.hash.substr(2);
	};
	window.onhashchange();
})();
